package com.itheima.controller;


import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.Md5Util;
import jakarta.validation.constraints.Pattern;
import jdk.jshell.execution.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Validated/*@Validated注解是Spring框架中的注解，用于开启方法级别的参数校验，@Pattern注解指定了用户名只能包含字母和数字*/
public class UserController {
    //注册登录
    @Autowired
    private UserService userservice;
    //登出
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        /*查询用户*/
        User u = userservice.findByUserName(username);
        if (u == null) {
            /*没有占用用户名*/
            /*注册*/
            userservice.register(username, password);
            return Result.success();
        } else {
            /*占用*/
            return Result.error("用户名被占用");
        }
    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password){
    /*查询用户*/
        User loginUser = userservice.findByUserName(username);
    /*判断用户*/
        if (loginUser == null){
            /*不存在该用户*/
        }
    /*判断密码*/
        if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){
            /*登录成功*/
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",loginUser.getId());
            claims.put("username",loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }
}
